import { getArticleList, getRefreshList } from '@/store/actions/home'
import { RootState } from '@/types/store'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import ArticleItem from '../ArticleItem'

import styles from './index.module.scss'

const ArticleList = ({ channelId }: { channelId: number }) => {
  const history = useHistory()
  const dispatch = useDispatch()

  // useEffect(() => {
  //   // 一进入页面获取当前频道下的最新数据
  //   dispatch(getArticleList(channelId, Date.now().toString()))
  // }, [dispatch, channelId])

  const channelArticles = useSelector(
    (state: RootState) => state.home.channelArticles
  )
  // 获取当前频道下的文章列表
  const { results = [], pre_timestamp } = channelArticles[channelId] || {}

  return (
    <div className={styles.root}>
      <PullToRefresh
        onRefresh={async () => {
          // 请求最新数据
          await dispatch(getRefreshList(channelId, Date.now().toString()))
        }}
      >
        {/* 文章列表中的每一项 */}
        {results.map((item) => {
          return (
            <div
              className="article-item"
              key={item.art_id}
              onClick={() => {
                history.push('/article/' + item.art_id)
              }}
            >
              <ArticleItem article={item} type={item.cover.type} />
            </div>
          )
        })}
        {/* 这个组件只要进入可视区了 表示列表到底了, 就需要加载更多数据了... */}
        <InfiniteScroll
          hasMore={pre_timestamp !== null}
          loadMore={async () => {
            // console.log(111)
            await dispatch(
              getArticleList(channelId, pre_timestamp || Date.now().toString())
            )
          }}
        ></InfiniteScroll>
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
